package com.beanpostprocessor;

import com.aop.AuditAnnotation;
import com.aop.RiskControlConstants;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

@Component
public class CheckAuditAnnotationBeanPostProcessor implements BeanPostProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(CheckAuditAnnotationBeanPostProcessor.class);
    private static final Set<RiskControlConstants.BizType> bizTypeSet = new HashSet<>();

    public static Set<RiskControlConstants.BizType> getBizTypeSet(){
        return bizTypeSet;
    }

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        Method[] declaredMethods = o.getClass().getDeclaredMethods();
        if (ArrayUtils.isNotEmpty(declaredMethods)) {
            for (Method declaredMethod : declaredMethods) {
                AuditAnnotation annotation = declaredMethod.getDeclaredAnnotation(AuditAnnotation.class);
                if (annotation != null) {
                    if(annotation.businessType()!=null){
                        LOGGER.info("============businessType.code:{}", annotation.businessType().getCode());
                        bizTypeSet.add(annotation.businessType());
                    }

                    int length1 = ArrayUtils.getLength(annotation.approveContentKey());
                    int length2 = ArrayUtils.getLength(annotation.approveContentValue());

                    if (length1 != length2) {
                        throw new RuntimeException(o.getClass() + " AuditAnnotation 注解配置异常");
                    }
                }
            }
        }
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        return o;
    }
}
